import os
import json
import csv


def process():
    # 输入目录路径
    directory = "cache"  # 替换为实际的目录路径
    output_file = directory + "/output.csv"  # 输出CSV文件名

    # 准备写入CSV文件
    csv_headers = ['uid', 'cate', 'nickname', 'handle', 'email', 'followers', 'views', 'platform', 'country']

    with open(output_file, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=csv_headers)
        writer.writeheader()

        # 读取目录下的所有文件
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            if os.path.isfile(file_path) and filename.endswith('.txt'):
                with open(file_path, 'r', encoding='utf-8') as file:
                    data = json.load(file)
                    data = json.loads(data)
                    for item in data:
                        row = {
                            'uid': item['uid'],
                            'cate': item['cate'],
                            'nickname': item['nickname'],
                            'handle': item['handle'],
                            'email': item['email'],
                            'followers': item['followers'],
                            'views': item['views'],
                            'platform': item['platform'],
                            'country': item['country']
                        }
                        writer.writerow(row)

    print(f"CSV文件已生成: {output_file}")
